package array.binarySearch;

/**
 * 给定一个按照升序排列的整数数组 nums，和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
 * <p>
 * 如果数组中不存在目标值 target，返回[-1, -1]。
 */
public class N34_SearchRange {
    public int[] searchRange(int[] nums, int target) {
        // 先找到边界，这里得到的边界是不等于target的边界（leftBorder<target rightBorder>target）
        int rightBorder = getRightBorder(nums, target);
        int leftBorder = getLeftBorder(nums, target);
        if (rightBorder == -2 || leftBorder == -2) // 如果边界索引有一个是-2，也就是查找的值不在数组范围内
            return new int[]{-1, -1};
        if (rightBorder - leftBorder > 1) // 如果两边界的差大于1也就是找到了
            return new int[]{leftBorder + 1, rightBorder - 1};
        return new int[]{-1, -1}; // 最后一种情况，target在数组范围内但是没有该值
    }

    // 查找右边界
    private int getRightBorder(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        int rightBorder = -2;
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (nums[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
                rightBorder = left;
            }
        }
        return rightBorder;
    }

    // 查找左边界
    private int getLeftBorder(int[] nums, int target) {
        int left = 0, right = nums.length - 1, leftBorder = -2;
        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
                leftBorder = right;
            }
        }
        return leftBorder;
    }

    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int target = 9;
        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();

        N34_SearchRange solution = new N34_SearchRange();
        int[] result = solution.searchRange(nums, target);
        System.out.println("[" + result[0] + ", " + result[1] + "]");
    }
}
